#pragma once
#include<iostream>
#include<functional>
#include"Log.hpp"
#include"InetAddr.hpp"
#include"Protocol.hpp"
#include"NetCal.hpp"


using namespace socket_ns;
//改自cal_server-Service
class PackageParse
{
public:

    void Excute(Connection* conn)
    {
        // LOG(DEBUG,"in EXCUTE\n");
        while(true)
        {   

            std::string json=Decode(conn->InBuffer());
            // LOG(DEBUG,"jsonsize:%d\n",json.size());
            if(json.empty())break;

            auto req=Factory::BuildRequestDefault();
            req->DeSerialize(json);

            // auto resp=_process(req);  
            auto resp=_cal.Calculator(req);
            std::cout<<"json:\n"<<json<<std::endl; 

            std::string respjson;
            resp->Serialize(&respjson);

            respjson=Encode(respjson);
            std::cout<<"respjson:\n"<<respjson<<std::endl;

            //添加到输出缓冲区
            conn->AppendOutBuffer(respjson);
            // break;
        }   
        // LOG(DEBUG,"Excute Outbuffer:%s\n",conn->OutBuffer().c_str());
        //至少处理了一个请求，至少一个应答在输出缓冲区
        // if(!conn->OutBuffer().empty())conn->_handler_sender(conn);//直接发送，不适合于多线程并发
        //只添加对写事件的关心，这样发送和接受都是由Reactor处理，多线程只负责安全的处理请求和应答
        if(!conn->OutBuffer().empty())
            conn->EnableConnectionReadWrite(conn->Sockfd(),true,true);
    }

private:
    NetCal _cal;
};